package vip.xiaonuo.smzq.core.gson;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * LocalDateAdapter
 *
 * @author eomer
 * @date 2020/6/26 15:38
 */
public class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
    @Override
    public JsonElement serialize(Date localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return new JsonPrimitive(df.format(new java.util.Date(localDateTime.getTime())));
    }

    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String datetime = json.getAsJsonPrimitive().getAsString();
        if (datetime == null || "".equals(datetime)) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        try {
            Date date = new Date(simpleDateFormat.parse(datetime).getTime());
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
